package com.fred.util

import com.fred.bean.InstallBean
import com.fred.bean.MessageBean
import com.fred.xlog.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader

object BundleToolUtil {
    private val bundleFilePath by lazy {
        val rootPath = Util.resourcesPath
        val path = "${rootPath}bundletool-1.14.0.jar"
        val file = File(path)
        if (file.exists()){
            file.absolutePath
        } else {
            ""
        }
    }

    suspend fun buildApks(installBean:InstallBean): MessageBean = withContext(Dispatchers.IO) {
        val result = MessageBean()
        if (bundleFilePath.isNotEmpty()){
            val start = System.currentTimeMillis()
            val apks = File(installBean.apksPath,"install.apks")
            val process = ProcessBuilder().command("java","-jar",bundleFilePath,"build-apks","--overwrite",
                "--bundle=${installBean.aabFile?.absolutePath?:""}",
                "--output=${apks.absolutePath}",
                "--ks=${installBean.keyStorePath}",
                "--ks-pass=pass:${installBean.keyStorePassword}",
                "--ks-key-alias=${installBean.alias}",
                "--key-pass=pass:${installBean.aliasPassword}",
                "--connected-device",
                "--device-id=${installBean.phone?.usbName}")
                .start()
            temp(process, result, start)
            installBean.installPath = apks.absolutePath
        }else {
            result.code = -1
            result.message.add("")
        }
        result
    }

    suspend fun installApks(installBean:InstallBean): MessageBean = withContext(Dispatchers.IO) {
        val result = MessageBean()
        if (bundleFilePath.isNotEmpty()){
            val start = System.currentTimeMillis()
            val process = ProcessBuilder().command("java","-jar",bundleFilePath,"install-apks",
                "--apks=${installBean.installPath}",
                "--adb=${installBean.adbFilePath}",
                "--device-id=${installBean.phone?.usbName}")
                .start()
            temp(process, result, start)
        }else {
            result.code = -1
            result.message.add("")
        }
        result
    }

    private fun temp(process:Process,result:MessageBean,start:Long) {
        val successResult = BufferedReader(InputStreamReader(process.inputStream))
        val errorResult = BufferedReader(InputStreamReader(process.errorStream))
        var read: String?
        while (successResult.readLine().also { read = it } != null) {
            result.message.add(read?:"")
            Log.i("Success:${read}")
        }

        while (errorResult.readLine().also { read = it } != null) {
            if (read?.contains("The APKs have been extracted in the directory") == true) {
                result.code = 0
            } else {
                result.code = -1
            }
            result.message.add(read?:"")
            Log.i("error:${read}")
        }
        val useTime = (System.currentTimeMillis() - start)/1000f
        result.useTime = useTime
    }

}

fun main(){
//    BundleToolUtil.buildApks()
}